package com.xiaolong.redis.util;

import org.springframework.data.redis.core.*;

import java.util.concurrent.TimeUnit;


@SuppressWarnings("unchecked")
public class CacheUtil {

    public static RedisTemplate<String, Object> template;
    public static HashOperations<String, Object, Object> hashOperations;
    public static ValueOperations<String, Object> valueOperations;
    public static ZSetOperations<String, Object> zSetOperations;
    public static ListOperations<String, Object> listOperations;


    public static void init(RedisTemplate<String, Object> redisTemplate) {
        template = redisTemplate;
        hashOperations = template.opsForHash();
        valueOperations = template.opsForValue();
        zSetOperations = template.opsForZSet();
        listOperations = template.opsForList();
    }

    public static RedisTemplate<String, Object> getInstance() {
        return template;
    }

    public static HashOperations<String, Object, Object> hashOperations() {
        return hashOperations;
    }

    public static ValueOperations<String, Object> valueOperations() {
        return valueOperations;
    }

    public static void del(String key) {
        template.delete(key);
    }

    public static boolean contains(String key) {
        return Boolean.TRUE.equals(template.hasKey(key));
    }


    public static <T> T strValue(String key) {
        return (T) valueOperations.get(key);
    }

    public static <T> void fillStr(String key, T value) {
        valueOperations.set(key, value);
    }

    public static <T> void fillStr(String key, T value, long timeOut) {
        valueOperations.set(key, value, timeOut, TimeUnit.SECONDS);
    }

    public static <T> T hashValue(String key, Object hashKey) {
        return (T) hashOperations.get(key, hashKey);
    }

    public static <T> void fillHash(String key, Object hashKey, T value) {
        hashOperations.put(key, hashKey, value);
    }

    public static <T> void fillHash(String key, Object hashKey, T value, long timeOut) {
        hashOperations.put(key, hashKey, value);
        template.expire(key, timeOut, TimeUnit.SECONDS);
    }

    public static boolean containsHash(String key, String prefix) {
        return hashOperations.hasKey(key, prefix);
    }

    public static <T> void delHash(String key) {
        hashOperations.delete(key);
    }


}
